<template>
  <el-form :model="condition" :inline="true">
    <el-form-item label="姓名">
      <el-input v-model="condition.name" placeholder="请输入姓名" clearable/>
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="condition.sex" placeholder="请选择性别" clearable>
        <el-option v-for="(s,index) in sexArr" :label="s" :value="index + ''"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="condition.state" placeholder="请选择状态" clearable>
        <el-option v-for="(s,index) in states" :label="s" :value="index + ''"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">
        <el-icon>
          <component is="search" />
        </el-icon>
        查询
      </el-button>
      <el-button @click="reset">
        <el-icon>
          <component is="refreshLeft" />
        </el-icon>
        重置
      </el-button>
      <el-button type="success" @click="showAddDialog">
        <el-icon>
          <component is="circlePlus" />
        </el-icon>
        新增
      </el-button>
    </el-form-item>
  </el-form>
  <div class="operation-container">
    <el-button type="success" @click="showImportDialog">导入</el-button>
    <el-button type="success" @click="exportUser">导出</el-button>
    <el-button-group>
      <el-button type="primary" icon="CircleClose" @click="changeUserState(0)">冻结</el-button>
      <el-button type="primary" icon="CircleCheck" @click="changeUserState(1)">解冻</el-button>
      <el-button type="danger" icon="Delete" @click="deleteUsers(selectedUsers.value.map(user => user.username))">删除</el-button>
    </el-button-group>
    <el-pagination small background v-show="total > 0"
                   v-model:current-page="currentPage"
                   v-model:page-size="pageSize"
                   :page-sizes="pageSizes"
                   layout="total, sizes, prev, pager, next"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />
  </div>
  <el-table :data="users" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column label="用户名" property="username" />
    <el-table-column label="姓名" property="name"/>
    <el-table-column label="性别">
      <template #default="scope">
        {{scope.row.sex === 0 ? '男' : scope.row.sex === 1 ? '女' : '其他'}}
      </template>
    </el-table-column>
    <el-table-column label="年龄" property="age"/>
    <el-table-column label="联系电话" property="phone"/>
    <el-table-column label="邮箱" property="email" show-overflow-tooltip/>
    <el-table-column label="状态">
      <template #default="scope">
        {{scope.row.state === 0 ? '冻结' : '正常'}}
      </template>
    </el-table-column>
    <el-table-column label="角色">
      <template #default="scope">
        {{scope.row.role?.name}}
      </template>
    </el-table-column>
    <el-table-column label="入职日期" property="entryTime"/>
    <el-table-column label="操作">
      <template #default="scope">
        <!--  scope.row就表示当前行的数据对象      -->
        <el-button link type="success" @click="editUser(scope.row)">编辑</el-button>
        <el-button link type="success" @click="deleteUsers([scope.row.username])">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <user-dialog :dialog-data="userData" @search-event="search"/>
  <file-chooser :dialog-data="importData" @search-event="search" />
</template>

<script setup lang="ts">

  import {ref} from "vue";
  import {doGet, doDelete, doPut } from '../../components/ajax'
  import { showConfirm } from '../../components/tip'
  import UserDialog from "./UserDialog.vue";
  import {ElMessage} from "element-plus";
  import FileChooser from "../../components/file/FileChooser.vue";

  const condition = ref({
    name: '',
    sex: '',
    state: ''
  })

  const sexArr = ref(['男', '女', '其他'])

  const states = ref(['冻结', '正常'])

  const users = ref([])

  const selectedUsers  = ref( [])

  const currentPage = ref(1)

  const pageSize = ref(50)

  const pageSizes = ref([50, 100, 200, 400])

  const total = ref(0)

  const userData = ref({
    visible: false,
    user: {},
    isUpdate: false
  })

  const importData = ref({
    visible: false,
    title: '导入用户信息',
    url: '/user/import'
  })

  const showImportDialog = () =>{
    importData.value.visible = true;
  }

  const handleSelectionChange = val => {
    selectedUsers.value = val;
  }

  const handleSizeChange = val => {
    currentPage.value = 1;
    pageSize.value = val;
    search()
  }

  const handleCurrentChange = val => {
    currentPage.value = val;
    search()
  }

  const search = () =>{
    doGet('/user', {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      name: condition.value.name,
      sex: condition.value.sex,
      state: condition.value.state
    }, resp => {
      users.value = resp.data.records
      total.value = resp.data.total
      selectedUsers.value = []
    })
  }

  const reset = () => {
    condition.value = {
      name: '',
      sex: '',
      state: ''
    }
  }

  const showAddDialog = () => {
    userData.value.isUpdate = false
    userData.value.visible = true
  }

  const  editUser = user => {
    userData.value.user = JSON.parse(JSON.stringify(user))
    userData.value.isUpdate = true
    userData.value.visible = true
  }

  const deleteUsers = usernames => {
    if(usernames.length === 0){
      ElMessage.error("请选择需要删除的用户信息");
      return;
    }
    showConfirm("提示", "确定要删除选择的用户信息吗?", () =>{
      doDelete("/user", {usernames: usernames}, resp =>{
        if(resp.data){
          ElMessage.success("删除成功");
          search()
        } else {
          ElMessage.error("删除失败");
        }
      })
    })
  }

  const changeUserState = state => {
    if(selectedUsers.value.length === 0){
      ElMessage.error("请选择需要" + (state === 0 ? '冻结' : '解冻') + "的用户信息")
      return;
    }
    doPut("/user/state",{
      usernames: selectedUsers.value.map(user => user.username),
      state: state
    }, resp => {
      if(resp.data){
        ElMessage.success((state === 0 ? '冻结' : '解冻') + "成功")
        search()
      } else {
        ElMessage.error((state === 0 ? '冻结' : '解冻') + "失败")
      }
    })
  }

  const exportUser = () => {
    //导出数据其实就是按照当前的条件去数据库查询出导出的数据
    let parameterInfo = "";
    Object.keys(condition.value).forEach(key => parameterInfo += key + "=" + condition.value[key] + "&");
    //下载的时候要注意，这里不是使用ajax请求，因此不会有前缀的拦截，这里需要手动加上前缀
    window.location.href = "/electronic/user/export?" + parameterInfo;
  }


  search()
</script>

<style scoped>
.el-form {
  border-bottom: 1px solid #ddd;
}

.el-pagination{
  float: right;
}

</style>
